package name.vaccari.matteo.tai.phonedirectory.htmlbuilder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class GenericElement implements HtmlBuilder {

	private final String name;
	private List<HtmlBuilder> children = new ArrayList<HtmlBuilder>();
	private List<String> attributeNames = new ArrayList<String>();
	private List<String> attributeValues = new ArrayList<String>();

	public GenericElement(String name) {
		this.name = name;
	}
	
	public HtmlBuilder add(HtmlBuilder ... children) {
		this.children.addAll(Arrays.asList(children));
		return this;
	}

	public String build() {
		String startTag = startTag();
		return startTag + "\n" + processChildren() + "</" + name + ">";
	}

	private String startTag() {
		String startTag = "<" + name + attributesList() + ">";
		return startTag;
	}

	private String attributesList() {
		String result = "";
		for (int i=0; i<attributeNames.size(); i++) {
			String name = attributeNames.get(i);
			String value = attributeValues.get(i);
			result += " " + name + "=\"" + value + "\"";			
		}
		return result;
	}

	private String processChildren() {
		String result = "";
		for (HtmlBuilder child : children) {
			result += child.build();
			result += "\n";
		}
		return result;
	}

	public HtmlBuilder with(String attributeName, String attributeValue) {
		attributeNames.add(attributeName);
		attributeValues.add(attributeValue);
		return this;
	}

}
